package com.clw.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

public class VerificationCodeUtils {
	public static String strCode = null;
	public static final char[] CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456".toCharArray();
	public static Random random = new Random();

	//获取六位随机数
	public static String getRandomString() {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0;i<4;i++) {
			buffer.append(CHARS[random.nextInt(CHARS.length)]);
		}
		strCode = buffer.toString();
//System.out.println("4位随机数："+strCode);
		return strCode;
	}

	//获取随机颜色
	public static Color getRandomColor() {
		return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
	}

	//返回某颜色的反色
	public static Color getReverseColor(Color c) {
		return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue());
	}

	//创建图片
	public ByteArrayInputStream createImage() {
		String randomString = getRandomString();//获取随机字符串

		int width = 100;//设置图片的宽度
		int height = 50;//高度

		Color color = getRandomColor();//获取随机颜色，作为背景色
		Color reverse = getReverseColor(color);//获取反色，用于前景色

		int fontSize=25;//字体大小
		Font font=new Font(Font.SANS_SERIF, Font.BOLD, fontSize);
		//创建一个彩色图片
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = image.createGraphics();//获取绘制对象
		g.setFont(font);//设置字体

		g.setColor(color);//设置颜色

		FontMetrics fontMetrics = g.getFontMetrics(font);

		int centerX = image.getWidth() / 2;
		int y=centerX - fontMetrics.getHeight() / 2;
		// 文字宽度
		int textWidth = fontMetrics.stringWidth(randomString);

		g.fillRect(0, 0, width, height);//绘制背景
		g.setColor(reverse);//设置颜色
		g.drawString(randomString, centerX - textWidth / 2, y);

		//最多绘制100个噪音点
		for (int i = 0,n = random.nextInt(100); i < n; i++) {
			g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
		}

		//返回验证码图片的流格式
		ByteArrayInputStream bais = convertImageToStream(image);

		return bais;

	}

	//将BufferedImage转换成ByteArrayInputStream
	private static ByteArrayInputStream convertImageToStream(BufferedImage image){
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ByteArrayInputStream inputStream = null;
		try {
			ImageIO.write(image,"JPEG",bos);
			byte[] bts = bos.toByteArray();
			inputStream = new ByteArrayInputStream(bts);

		} catch (IOException e) {
			e.printStackTrace();
		}
		return inputStream;
	}




}
